package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.data.Result;
import com.dongdongshop.data.ResultEnum;
import com.dongdongshop.pojo.seller.TbSeller;
import com.dongdongshop.service.SellerService;
import com.dongdongshop.shiro.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

@Controller
@RequestMapping("seller")
public class SellerController {
    @Reference
    private SellerService sellerService;

    private final Logger logger= LoggerFactory.getLogger(SellerService.class);

    @RequestMapping("shopLogin")
    public String shopLogin(){
        return "shoplogin";
    }

    @RequestMapping("index")
    public String index(){
        return "admin/index";
    }
    //登录
    @RequestMapping("toLogin")
    public String toLogin(String sellerId, String password, Model model){
        //使用Shiro登录，获取subject
        Subject subject = SecurityUtils.getSubject();
        //将参数封装到token里
        UsernamePasswordToken token = new UsernamePasswordToken(sellerId,password);
        try {
            //登录成功
            subject.login(token);
            return "admin/index";
        }catch (UnknownAccountException e){
            model.addAttribute("message","用户不存在");
            return "shoplogin";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("message","密码不正确");
            return "shoplogin";
        }
    }

    //注册
    @RequestMapping("register")
    public String register(){
        return "register";
    }

    @RequestMapping("toRegister")
    @ResponseBody
    public Result toRegister(TbSeller tbSeller){
        try {
            //添加盐
            String salt = ShiroUtils.generateSalt(6);
            System.out.println("盐" + salt);
            tbSeller.setSalt(salt);
            //添加密文
            String md5 = ShiroUtils.encryptPassword("MD5", tbSeller.getPassword(), salt, 3);
            System.out.println("密文 " + md5);
            tbSeller.setPassword(md5);
            sellerService.toRegister(tbSeller);
            return Result.response(ResultEnum.OK);
        }catch (Exception e){
            logger.info("系统错误",e);
            return Result.response(ResultEnum.FAIL);
        }
    }

}
